const { SuccessModel, ErrorModel } = require("../model/resModel");
const {
  getList,
  getDetail,
  deleteBlog,
  updateBlog,
  newBlog,
} = require("../controller/blog");
const loginCheck = require("../middleware/loginCheck");

const router = require('express').Router()
router.get('/allList', async (req, res, next) => {
  const data = await getList()
  if (data) {
    res.json(new SuccessModel(data));
  } else {
    res.json(new ErrorModel(data))
  }
})
router.get('/userBloglist', loginCheck, (req, res, next) => {
  let author = req.session.userName;
  const keyword = req.query.keyword;

  if (req.session.isAdmin === 1) {
    // 管理员查询所有博客
    author = ''
  }

  getList(author, keyword).then(data => {
    if (data) {
      res.json(new SuccessModel({ list: data, userName: req.session.userName }));
    } else {
      res.json(new ErrorModel(data))
    }
  })
})

router.get('/detail', async (req, res, next) => {
  const data = await getDetail(req.query.id)
  if (data) {
    res.json(new SuccessModel(data));
  } else {
    res.json(new ErrorModel(null, '博客不存在'))
  }
})

router.post('/new', loginCheck, (req, res, next) => {
  const { title, content } = req.body
  const author = req.session.userName
  newBlog(title, content, author).then(insertId => {
    if (insertId) {
      res.json(new SuccessModel('新增成功'));
    } else {
      res.json(new ErrorModel('新增失败'));
    }
  })
})

router.post('/update', loginCheck, (req, res, next) => {
  const id = req.query.id
  const { title, content } = req.body
  updateBlog(title, content, id, req.session.userName, req.session.isAdmin).then(insertId => {
    if (insertId) {
      res.json(new SuccessModel('更新成功'));
    } else {
      res.json(new ErrorModel('更新失败'));
    }
  })
})

router.post('/delete', loginCheck, (req, res, next) => {
  deleteBlog(req.query.id, req.session.userName, req.session.isAdmin).then(affectedId => {
    if (affectedId) {
      res.json(new SuccessModel('删除成功'));
    } else {
      res.json(new ErrorModel('删除失败'));
    }
  })
})

module.exports = router;